package model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * The DocVector class implements the vector representation of the documents in the Inverted Index.
 * It's a matrix that crosses the words with the files, having a 1 if the word exists in the file and 0 if doesn't.
 * @author Diogo Kiss and Valerio Lopes
 */
public class RepVetorial 
{

	private ArrayList<String> fileList;
	private TreeSet<String> wordList;
	private TreeMap<String,short[]> indice;
	
	private InvIndex originalIndex;
	
	public RepVetorial(InvIndex index)
	{
		//Retrieving the original file list
		this.fileList = index.getFileList();
		Collections.sort(index.getFileList());
		
		//Retrieving the words list
		this.wordList = new TreeSet<String>(index.indice.keySet());
		
		//Retrieving the original inverted Index
		this.originalIndex = index;
		
		//Instantiating the vector representation of the documents
		this.indice = new TreeMap<String,short[]>();
	}
	
	/**
	 * The create method builds the matrix, scanning the words list and the files list.
	 * For each word, it checks if it exists in all files, putting 1 for true and 0 for false.
	 * At the end, the matrix is built.
	 */	
	public void create()
	{
		for(String w: wordList)
		{
			//for each word, associate a array of short integers which will hold the values 0 or 1
			//each position in the array represents a file, in the same order as the ArrayList fileList
			indice.put(w, new short[fileList.size()]);
			int contador = 0;
			
			for(String f: fileList)
			{
				if(originalIndex.contains(w,f))
					indice.get(w)[contador] = 1;
				else
					indice.get(w)[contador] = 0;

				contador++;				
			}
		}
		
	}
	
	/**
	 * The contains method simply checks if the given word exists in the given file, looking in the matrix and not scanning the file.
	 * @param String word - the word to be checked.
	 * @param String fileName - the file to be checked.
	 * @return It returns 1 (the word exists in the file) or 0 (it doesn't).
	 */	
	public int contains(String word, String fileName)
	{
		String finalWord = word.toLowerCase().trim().replaceAll("\t", "");
		
		//retrieve the position of the specified file in the ArrayList fileList
		//remember that they're in the same order in the matrix
		int filepos = this.fileList.indexOf(fileName);
		
		if(indice.get(finalWord) != null) //the file contains the word
			return indice.get(finalWord)[filepos];
		else //it doesn't
			return 0;


	}
	
}
